package com.gitee.feizns.quickstart.ding.talk.api.top.api.v2.user;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiV2UserListRequest;
import com.dingtalk.api.response.OapiV2UserListResponse;
import com.gitee.feizns.quickstart.ding.talk.utils.Utils;
import lombok.SneakyThrows;

import java.util.ArrayList;

/**
 * 调用本接口获取指定部门中的用户详细信息。（/topapi/v2/user/list）
 * 接口路径：<a href="https://open.dingtalk.com/document/orgapp/queries-the-complete-information-of-a-department-user">获取部门用户详情（/topapi/v2/department/listsub）</a>
 * @link <a href="https://open.dingtalk.com/document/orgapp/queries-the-complete-information-of-a-department-user">服务端API 通讯录管理 用户管理 获取部门用户详情</a>
 * @author feizns
 * @since 2024/6/29
 */
public class List {

    /**
     * 默认大小
     */
    public static final long DEFAULT_SIZE = 100;

    /**
     * 调用本接口获取指定部门中的用户详细信息。
     * @param accessToken 访问令牌
     * @param req 要求
     * @return {@link OapiV2UserListResponse.PageResult}
     */
    @SneakyThrows
    public static OapiV2UserListResponse.PageResult execute(String accessToken, OapiV2UserListRequest req) {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/list");
        OapiV2UserListResponse rsp = client.execute(req, accessToken);
        return Utils.ifErrorThrow(rsp).getResult();
    }

    /**
     * 调用本接口获取指定部门中的用户详细信息。
     * @param accessToken 访问令牌
     * @param deptId 部门 ID
     * @param cursor 光标
     * @param size 大小
     * @return {@link OapiV2UserListResponse.PageResult}
     */
    @SneakyThrows
    public static OapiV2UserListResponse.PageResult execute(String accessToken, Long deptId, Long cursor, Long size) {
        OapiV2UserListRequest req = new OapiV2UserListRequest();
        req.setDeptId(deptId);
        req.setCursor(cursor);
        req.setSize(size);
        return execute(accessToken, req);
    }

    /**
     * v2 用户列表
     * @return {@link java.util.List}<{@link OapiV2UserListResponse.ListUserResponse}>
     */
    @SneakyThrows
    public static java.util.List<OapiV2UserListResponse.ListUserResponse> execute(String accessToken, Long deptId) {
        java.util.List<OapiV2UserListResponse.ListUserResponse> result = new ArrayList<>();
        long cursor = 0;
        OapiV2UserListResponse.PageResult pageResult;
        do {
            pageResult = execute(accessToken, deptId, cursor, DEFAULT_SIZE);
            result.addAll(pageResult.getList());
            cursor++;
        } while ( pageResult.getHasMore() );
        return result;
    }

}
